package io.gitee.bowen_lee.lbwio.groupboss_and_groupworker;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 创建线程(selector) 、bind() 、register()
 * 
 * @author Bowen
 * @since 2022-01-06 09:39:31
 */
public class SelectorThreadGroup {

  SelectorThread[] sts;
  /**
   * worker selector group
   */
  SelectorThreadGroup worker = null;

  volatile AtomicInteger xid;

  /**
   * 构造
   * 
   * @param num 线程数
   */
  public SelectorThreadGroup(int num) {
    sts = new SelectorThread[num];
    xid = new AtomicInteger(0);
    for (int i = 0; i < sts.length; i++) {
      sts[i] = new SelectorThread();
      new Thread(sts[i]).start();
    }
  }

  /**
   * 绑定
   * 
   * @param port 端口号
   */
  public void bind(int port) {
    try {
      ServerSocketChannel server = ServerSocketChannel.open();
      // 设置 非阻塞
      server.configureBlocking(false);
      server.bind(new InetSocketAddress(port));

      // 注册
      RegisterHandle.serverRegister(server);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 判断group是否为null
   * 
   * @param group
   * @return
   */
  public boolean notEmpty(SelectorThreadGroup group) {
    return group != null ? true : false;
  }

}
